#include "lb.h"

int LBLineClipTest(double p, double q, double &umax, double &umin)
{
    double r = 0.0;

    if (p < 0.0)
    {
        r = q / p;
        if (r > umin)
            return 0;
        else if (r > umax)
            umax = r;
    }

    else if (p > 0.0)
    {
        r = q / p;

        if (r < umax)
            return 0;
        else if (r < umin)
            umin = r;
    }

    else if (q < 0.0)
        return 0;
    return 1;
}

void LBLineClip(Polygon<double> region, Line<double> line)
{
    double xwl = region.left, xwr = region.right,
           ywb = region.bottom, ywt = region.top,
           x1 = line.start.x, y1 = line.start.y,
           x2 = line.end.x, y2 = line.end.y;
    double umax, umin, deltax, deltay, i1, j1;
    deltax = x2 - x1;
    deltay = y2 - y1;
    umax = 0.0;
    umin = 1.0;

    if (LBLineClipTest(-deltax, x1 - xwl, umax, umin))
    {
        if (LBLineClipTest(deltax, xwr - x1, umax, umin))
        {
            if (LBLineClipTest(-deltay, y1 - ywb, umax, umin))
            {
                if (LBLineClipTest(deltay, ywt - y1, umax, umin))
                {
                    i1 = int(x1 + umax * deltax + 0.5);
                    j1 = int(y1 + umax * deltay + 0.5);
                    x2 = int(x1 + umin * deltax + 0.5);
                    y2 = int(y1 + umin * deltay + 0.5);
                }

                Line<double> clipped({i1, j1}, {x2, y2});
                clipped.draw();
            }
        }
    }
}
